package com.oj.system.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oj.common.core.constants.CacheConstants;
import com.oj.common.core.domain.LoginUser;
import com.oj.common.core.domain.R;
import com.oj.common.core.domain.TableDataInfo;
import com.oj.common.core.enums.ResultCode;
import com.oj.common.core.utils.JwtUtils;
import com.oj.common.redis.service.RedisService;
import com.oj.common.security.exception.ServiceExpection;
import com.oj.common.security.service.TokenService;
import com.oj.system.domain.question.Question;
import com.oj.system.domain.question.dto.QuestionEditDTO;
import com.oj.system.domain.question.dto.QuestionQueryDTO;
import com.oj.system.domain.question.dto.QuestionSaveTO;
import com.oj.system.domain.question.es.QuestionES;
import com.oj.system.domain.question.vo.QuestionDetailVO;
import com.oj.system.domain.question.vo.QuestionVO;
import com.oj.system.elasticsearch.QuestionRepository;
import com.oj.system.manager.QuestionCacheManager;
import com.oj.system.mapper.QuestionMapper;
import com.oj.system.service.question.IQuestionService;
import com.oj.common.core.constants.Constants;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author bin
 * @Date 2025/4/28
 */
@Service
@RefreshScope
public class QuestionServiceImpl implements IQuestionService {


    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private TokenService tokenService;

    @Resource
    private QuestionRepository  questionRepository;

    @Resource
    private QuestionCacheManager questionCacheManager;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO, String token) {
        //可选参数   排除已选择题目
        String excludeIdStr = questionQueryDTO.getExcludeIdStr();
        if(StringUtils.isNotEmpty(excludeIdStr)){
            String[] excludeIds = excludeIdStr.split(Constants.SPLIT_SEM);
            //stream流
            Set<Long> excludeIdSet = Arrays.stream(excludeIds)
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());
            questionQueryDTO.setExcludeIdSet(excludeIdSet);
        }
        //分页插件
        PageHelper.startPage(questionQueryDTO.getPageNum(),questionQueryDTO.getPageSize());
        //以下内容为尝试 写xml文件其实更方便
        LambdaQueryWrapper<Question> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        String userId = JwtUtils.getUserId(JwtUtils.parseToken(token, secret));
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        lambdaQueryWrapper.like(StringUtils.isNotBlank(questionQueryDTO.getTitle()),Question::getTitle,questionQueryDTO.getTitle())
                .eq(questionQueryDTO.getDifficulty() != null ,Question::getDifficulty,questionQueryDTO.getDifficulty())
                .eq(Question::getCreateBy,Long.valueOf(userId))
                .notIn(CollectionUtil.isNotEmpty(questionQueryDTO.getExcludeIdSet()),Question::getQuestionId, questionQueryDTO.getExcludeIdSet())
                .orderBy(true,false,Question::getCreateTime);
        List<Question> questions = questionMapper.selectList(lambdaQueryWrapper);
        if(CollectionUtil.isEmpty(questions)){
            return TableDataInfo.empty();
        }
        List<QuestionVO> questionsVO = new ArrayList<>();
        //Question 转为 QuestionVO
        for (Question question : questions) {
            QuestionVO questionVO = new QuestionVO();
            questionVO.setQuestionId(question.getQuestionId());
            questionVO.setTitle(question.getTitle());
            questionVO.setDifficulty(question.getDifficulty());
            questionVO.setCreateTime(question.getCreateTime());
            questionVO.setNickName(tokenService.getLoginUser(token, secret).getNickName());
            questionsVO.add(questionVO);
        }
        // 获取符合条件的数据总数
        new PageInfo<>(questionsVO).getTotal();
        return TableDataInfo.success(questionsVO, new PageInfo<>(questionsVO).getTotal());
    }

    public boolean add(QuestionSaveTO questionDTO) {
        LambdaQueryWrapper<Question> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Question::getTitle,questionDTO.getTitle());
        if(CollectionUtil.isNotEmpty(questionMapper.selectList(lambdaQueryWrapper))){
            //失败 资源已重复
            throw new ServiceExpection(ResultCode.FAILED_ALREADY_EXISTS);
        }
        Question question = new Question();
        //把QuestionSaveTO 转为Question
        BeanUtil.copyProperties(questionDTO,question);

        int insert = questionMapper.insert(question);
        if(insert <= 0){
            return false;
        }
        // 添加的题目应该也在es中同步存储
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(question,questionES);
        questionRepository.save(questionES);
        // TODO redis中维护的题目顺序表
        questionCacheManager.addCache(question.getQuestionId());

        return true;
    }

    @Override
    public R<QuestionDetailVO> detail(Long questionId) {
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        Question question = questionMapper.selectById(questionId);
        if (question != null){
            BeanUtil.copyProperties(question,questionDetailVO);
            return R.ok(questionDetailVO);
        }
        return R.fail(ResultCode.FAILED_NOT_EXISTS);
    }

    @Override
    public R<Void> delete(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if (question == null){
            return R.fail(ResultCode.FAILED_NOT_EXISTS);
        }
        // 删除时es中同步删除
        questionRepository.deleteById(questionId);
        // redis中维护的题目顺序表
        questionCacheManager.deleteCache(questionId);

        if (questionMapper.deleteById(questionId) > 0){
            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R<Void> edit(QuestionEditDTO questionDTO) {
        Question question = questionMapper.selectById(questionDTO.getQuestionId());
        if (question == null){
            throw new ServiceExpection(ResultCode.FAILED_NOT_EXISTS);
        }
        //BeanUtil.copyProperties(questionDTO,question);
        question.setTitle(questionDTO.getTitle());
        question.setDifficulty(questionDTO.getDifficulty());
        question.setTimeLimit(questionDTO.getTimeLimit());
        question.setSpaceLimit(questionDTO.getSpaceLimit());
        question.setContent(questionDTO.getContent());
        question.setQuestionCase(questionDTO.getQuestionCase());
        question.setDefaultCode(questionDTO.getDefaultCode());
        question.setMainFunc(questionDTO.getMainFunc());

        //编辑的时候要将ES中的数据和编辑后的数据同步
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(question,questionES);
        questionRepository.save(questionES);

        if (questionMapper.updateById(question) > 0){
            return R.ok();
        }
        return R.fail();
    }
}
